//异步任务三种方式

const fs = require('fs')

//正常使用回调函数
exports.callback = done => {
    console.log('callback task')
    done()
}

exports.callback_err = done => {
    console.log('callback_err task')
    done(new Error('failed callback task'))
}

//使用promise方式
exports.promise = () => {
    console.log('promise task')
    return Promise.resolve()
}

exports.promise_err = () => {
    console.log('promise_err task')
    return Promise.reject(new Error('failed promise task'))
}

//使用async 和 await 方式实现

let timeOut = time => {
    return new Promise(resolve => {
        setTimeout(resolve, time)
    })
}

exports.async = async () => {
    await timeOut(1000)
    console.log('async task')
}

//使用stream的方式实现异步
exports.stream = () => {
    const readStream = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    readStream.pipe(writeStream)
    return readStream
}

//模拟实现gulp结束异步
exports.stream1 = done => {
    const readStream = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    readStream.pipe(writeStream)
    //gulp 主要是通过  获取到stream后，注册一个end事件， 在end事件中结束任务
    readStream.on('end', () => {
        console.log('end task')
        done()
    })
}
